package com.vinaprime.primeschedule.presentation;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.vinaprime.primeschedule.businesslayer.VPContact_BL;
import com.vinaprime.primeschedule.businesslayer.VPGroupHeader_BL;
import com.vinaprime.primeschedule.entities.VPContact;
import com.vinaprime.primeschedule.entities.VPGroupHeader;

public class VPContactGroupDetailsActivity extends Activity {
	public final static String CONTACT_LIST_START = "com.vinaprime.primeschedule.presentation.MESSAGE";
	public final static String CONTACT_LIST_CHECK = "com.vinaprime.primeschedule.presentation.MESSAGE";
	public final static String CONTACT_GROUP_ID = "com.vinaprime.primeschedule.presentation.MESSAGE";
	int	_idConntactGroup;
	String[]  _StringId;
	String[]  _StringLineId;
	ApplicationInformation appinfo;
	String path;
	VPGroupHeader_BL contactGroupBL;
	VPContact_BL contactBL;
	VPGroupHeader contactGroupHeader;
	
	EditText edtGroupName ;
	EditText edtGroupDescription;	
    ListView listView;
    List<VPContact> listContactOfGroup;
    List<VPContact> listContactFilter;
    List<VPContact> listContactAll;
    VPContactArrayAdapter _adapter_array;
    AutoCompleteTextView _autoTextView;
    
    static final int LIST_VIEW_ID = 1;
    
    ListViewContactGroupLineAdapter list_adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpcontact_group_details);
		ActionBar actionBar = getActionBar();
		Drawable d=getResources().getDrawable(R.raw.background_top);  
		actionBar.setBackgroundDrawable(d);
		//-----------------------------------//
		appinfo = new ApplicationInformation(this);
		path = appinfo.getDBPath();
		Intent intent = getIntent();		
		_StringId =intent.getStringArrayExtra(VPContactGroupActivity.CONTACT_GROUP_ID);
		_idConntactGroup = Integer.parseInt(_StringId[0]);
		//------------------------------------//
		contactBL = new VPContact_BL(this,  path + "databases/");
		try {
			
			listContactAll = contactBL.getAllContact();
			
			showListLine();
			
			_autoTextView = (AutoCompleteTextView)findViewById(R.id.autoComplete_Filter);
			
			listContactFilter = new ArrayList<VPContact>();
			listContactFilter = getListContactNotInGroup(listContactOfGroup);
			showArrayAdatper(listContactFilter);
			
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//------------------------------------//
		
		
		/*
		 * Xu ly su kien cua image
		 */
			ImageView _imgV = (ImageView)findViewById(R.id.imageView_addPeople);
			_imgV.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Show list contact to choose into this groups
			        listContactFilter = getListContactNotInGroup(listContactOfGroup);
			     	Serializable _listSend = (Serializable)listContactFilter;
					Intent intentChildCheck = new Intent(getApplicationContext(), VPContactListCheckActivity.class);
					intentChildCheck.putExtra(CONTACT_LIST_START, _listSend);				
					startActivityForResult(intentChildCheck, 2);
				}
			});
			
			
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == 2 )
		{
			if(null!=data)
			{
				
				//ArrayList<Parcelable> messageRecive = data.getParcelableArrayListExtra(CONTACT_LIST);
				List<VPContact> _list = (List<VPContact>)data.getSerializableExtra(CONTACT_LIST_CHECK);
				int rowcount = _list.size();
				for (int i = 0;i<rowcount;i++)
				{
					//listContactOfGroup.add(_list.get(i));	
					list_adapter.listContact.add(i,_list.get(i));
				}
				//list_adapter = new  ListViewContactGroupLineAdapter(listContactOfGroup,this);
				list_adapter.notifyDataSetChanged();
				listView.setAdapter(list_adapter);
				listView.invalidateViews();
				//Refresh listViewFilter
				listContactFilter = getListContactNotInGroup(listContactOfGroup);
				showArrayAdatper(listContactFilter);
			}
		}
		
		
	};
	public List<VPContact> getListContactNotInGroup(List<VPContact> _listInGroup)
	{
		List<VPContact> list = new ArrayList<VPContact>();
		
		
		int row_count_all = listContactAll.size();
		int row_count_list = _listInGroup.size();

		for(int i=0;i<row_count_all;i++)
		{
			int flag = 0;
			for(int j=0;j<row_count_list;j++)
			{
				if (listContactAll.get(i).getVpcID() == _listInGroup.get(j).getVpcID())
				{
					flag = 1;
					break;
				}
			}
			if(flag == 0)
			{
				list.add(listContactAll.get(i));
			}
			
		}
		return list;
	}
	private void showListLine()
	{
				contactGroupBL = new VPGroupHeader_BL(this, path+"databases/")	;
				edtGroupName = (EditText)findViewById(R.id.edttext_GroupHeaderName);	
				edtGroupDescription = (EditText)findViewById(R.id.edttext_GroupHeaderDescription);
				
				
				contactGroupHeader = new VPGroupHeader();
				contactGroupHeader =  contactGroupBL.getGroupHeaderbyID(_idConntactGroup);
				edtGroupName.setText(contactGroupHeader.getVpghName());
				edtGroupDescription.setText(contactGroupHeader.getVpghDescription());
					
				
				//Add list contact line-----------
				try {
					listContactOfGroup = contactGroupBL.getAllContactFromGroup(_idConntactGroup);
					listView = (ListView) findViewById(R.id.listView_GroupLineList);
					list_adapter = new  ListViewContactGroupLineAdapter(listContactOfGroup,this);
					listView.setAdapter(list_adapter);
	
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.action_bar_save_cancel, menu);
		return true;
	}
	
	public void showArrayAdatper(List<VPContact> _listContactFilter)
	{
		
		//listContactFilter = (ArrayList<VPContact>)listContactOfGroup;
		_adapter_array = new VPContactArrayAdapter(this, R.layout.activity_vpcontact_sub, (ArrayList<VPContact>)_listContactFilter);
		
		OnItemClickListener itemClickListenerAuto = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
            	VPContact _vp = _adapter_array.contactList.get(position);
            	_autoTextView.setText("");
            	           	
            	//Add list contact of group
            	list_adapter.listContact.add(0, _vp);
             	list_adapter.notifyDataSetChanged();
				listView.setAdapter(list_adapter);
				listView.invalidateViews();
				//Refresh list contact filter
				listContactFilter = getListContactNotInGroup(listContactOfGroup);
				showArrayAdatper(listContactFilter);
			
            }
        };

        _autoTextView.setOnItemClickListener(itemClickListenerAuto);
        _autoTextView.setAdapter(_adapter_array);
		
		
	}
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.action_save:
	    	   //update header
	    		contactGroupHeader.setVpghName(edtGroupName.getText().toString());
	    		contactGroupHeader.setVpghDescription(edtGroupDescription.getText().toString());
	    		contactGroupBL.updateGroupHeader(contactGroupHeader);
	    	
	    		//update listContactOfGroup
	    		contactGroupBL.updateContactInGroup(contactGroupHeader.getVpghId(),listContactOfGroup);
	    		
	    		//Tra ve VPContactGroupActivity
	    		Intent intentFatherGroup = new Intent();
		    	intentFatherGroup.putExtra(CONTACT_GROUP_ID, _idConntactGroup);
				setResult(8,intentFatherGroup);
			   	finish();
	      break;
	    case R.id.action_cancel:
	    		finish();
	      	break;
	    default:
	    	break;
	    }

	    return true;
	  } 
	
	private class ListViewContactGroupLineAdapter extends BaseAdapter {
		 
		VPContact_BL contactBL;
	    Context context;
	    List<VPContact> listContact;
	    public ListViewContactGroupLineAdapter(List<VPContact> _listContact,Context _context) {
	    	listContact = _listContact;
	        context=_context;
	        
	    }
	    @Override
	    public int getCount() {
	 
	        return listContact.size();
	    }

	    @Override
	    public Object getItem(int position) {
	        // TODO Auto-generated method stub
	       return listContact.get(position);
	    }
	 
	    @Override
	    public long getItemId(int position) {
	        // TODO Auto-generated method stub
	    	int vpglID = listContact.get(position).getVpcID();
			return vpglID;
	    	 
	    }

	 
	    @Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
	 
	        // create a new LayoutInflater
	        LayoutInflater inflater = (LayoutInflater) context
	                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	 
	        View listView;
	        listView = null;
	        byte [] imagebyte = null;
	        convertView = null;// avoids recycling of grid view
	        if (convertView == null) {
	 
	        	listView = new View(context);
	            // inflating list view item
	        	listView = inflater.inflate(R.layout.activity_vpcontact_group_details_line, null);
	        	
	        	//Tao VPGroupHeader
	        	VPContact _vpContact = new VPContact();
	        	_vpContact = (VPContact)getItem(position);

	        	
	        	TextView textViewName = (TextView) listView.findViewById(R.id.textView_ContactName);
	        	textViewName.setText(String.valueOf(_vpContact.getVpcLastName()+" "+_vpContact.getVpcFistName()));
	        	
	        	TextView textViewId = (TextView) listView.findViewById(R.id.textView_ID);
	        	textViewId.setText(String.valueOf(_vpContact.getVpcID()));
	       
	            // set value into textview
	            TextView textView = (TextView) listView.findViewById(R.id.textView_ContactEmail);
	            textView.setText(_vpContact.getVpcEmail());		
	            
	            ImageView imgView = (ImageView)listView.findViewById(R.id.image_Contact);       
	            if (_vpContact.getVpcImage()!= null) {
	            	imagebyte = _vpContact.getVpcImage();
	            	imgView.setImageBitmap(BitmapFactory.decodeByteArray(imagebyte, 0, imagebyte.length));
				} else {
		           
		            imgView.setImageResource(R.raw.user1);
				}
	            
	            ImageView _imgV = (ImageView)listView.findViewById(R.id.image_delete);
	            
	            _imgV.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						listContact.remove(position);
						notifyDataSetChanged();
					}
				});
	            
	        }
	 
	        return listView;
	    }
	}
	
	private class VPContactArrayAdapter extends ArrayAdapter<VPContact> implements Filterable{
		  
		  public ArrayList<VPContact> contactList;
		  public ArrayList<VPContact> contactListAll;
		  private ItemsFilter mFilter;
		  int _childView;
		  Context context;
		  public VPContactArrayAdapter(Context context, int _ChildView,  ArrayList<VPContact> contactList) 
		  {
			   super(context, _ChildView, contactList);
			   this.context = context;
			   this.contactList = new ArrayList<VPContact>();
			   this.contactList.addAll(contactList);
			   this.contactListAll = new ArrayList<VPContact>();
			   this.contactListAll.addAll(contactList);
			   this._childView = _ChildView;
		  }
		  
		  private class ViewHolder {
		   TextView  id;
		   TextView name;
		   TextView email;
		   ImageView img;
		   
		  }
		  
		  @Override
		  public View getView(int position, View convertView, ViewGroup parent) {
			
			  byte [] imagebyte = null;
		   ViewHolder holder = null;
		   Log.v("ConvertView", String.valueOf(position));
		   if (convertView == null) {
			   LayoutInflater inflater = (LayoutInflater) context
				        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				 convertView = inflater.inflate(_childView, null);
		  
		   holder = new ViewHolder();
		   holder.id = (TextView) convertView.findViewById(R.id.textView_ID);
		   holder.name = (TextView) convertView.findViewById(R.id.textView_Ho);
		   holder.email = (TextView) convertView.findViewById(R.id.textView_Email);
		   holder.img = (ImageView) convertView.findViewById(R.id.image_Contact);
		   convertView.setTag(holder);
		   }
		   else {
		    holder = (ViewHolder) convertView.getTag();
		   }
		  
		   VPContact _contact = contactList.get(position);
		   holder.id.setText(String.valueOf(_contact.getVpcID()));
		   holder.name.setText(_contact.getVpcLastName()+" "+_contact.getVpcFistName());
		   holder.email.setText(_contact.getVpcEmail());
		   
		   if (_contact.getVpcImage()!= null) {
	       	imagebyte = _contact.getVpcImage();
	       	holder.img.setImageBitmap(BitmapFactory.decodeByteArray(imagebyte, 0, imagebyte.length));
			} else {
	          
				holder.img.setImageResource(R.raw.user1);
			}
			
	     
		   holder.name.setTag(_contact);
		  
		   return convertView;
		  
		  }
		  
		  /**
	       * Implementing the Filterable interface.
	       */
	      public Filter getFilter() {
	          if (mFilter == null) {
	              mFilter = new ItemsFilter();
	          }
	          return mFilter;
	      }

	      /**
	       * Custom Filter implementation for the items adapter.
	       *
	       */
	      private class ItemsFilter extends Filter {
	    	  @Override
	    	   protected FilterResults performFiltering(CharSequence constraint) {
	    	 
	    	    FilterResults result = new FilterResults();
	    	    
	    	    if(constraint != null && constraint.toString().length() > 0)
	    	    {
		    	    ArrayList<VPContact> filteredItems = new ArrayList<VPContact>();
		    	    int row_count = contactListAll.size();
		    	    for(int i = 0; i < row_count; i++)
		    	    {
		    	     VPContact co = contactListAll.get(i);
		    	     String _name = co.getVpcLastName().toLowerCase() +" "+co.getVpcFistName().toLowerCase() ;
		    	     String _s = constraint.toString().toLowerCase();
		    	     if(_name.contains(_s))
		    	      filteredItems.add(co);
		    	    }
		    	    result.count = filteredItems.size();
		    	    result.values = filteredItems;
	    	    }
	    	    else
	    	    {
		    	     synchronized(this)
		    	     {
		    	      result.values = contactListAll;
		    	      result.count = contactListAll.size();
		    	     }
	    	    }
	    	    return result;
	    	   }
	    	 
	    	   @SuppressWarnings("unchecked")
	    	   @Override
	    	   protected void publishResults(CharSequence constraint,
	    	     FilterResults results) {
	    	 
	    	    if (results != null && results.count > 0) {
		    	    	clear();
		    	    	contactList = (ArrayList<VPContact>)results.values;
		        	    notifyDataSetChanged();
		        	    int row_count = contactList.size();
		        	    for(int i = 0; i < row_count; i++)
		        	     add(contactList.get(i));
		        	    notifyDataSetInvalidated();
	            } else {
	            	
	                notifyDataSetInvalidated();
	            }
	    	    
	    	    
	    	   }
	    	  }
	}

}
